/**
 * 音频播放工具类
 */
export class AudioPlayer {
  constructor() {
    this.audioContext = null
    this.currentSource = null
    this.isPlaying = false
  }

  /**
   * 初始化音频上下文
   */
  async initialize() {
    try {
      this.audioContext = new (window.AudioContext || window.webkitAudioContext)()
      return true
    } catch (error) {
      console.error('初始化音频播放器失败:', error)
      return false
    }
  }

  /**
   * 播放音频数据
   */
  async playAudio(audioData) {
    if (!this.audioContext) {
      await this.initialize()
    }

    try {
      // 停止当前播放
      this.stop()

      console.log('开始解码音频数据，大小:', audioData.byteLength)

      // 解码音频数据
      const audioBuffer = await this.audioContext.decodeAudioData(audioData)
      console.log('音频解码成功，时长:', audioBuffer.duration, '秒')

      // 创建音频源
      this.currentSource = this.audioContext.createBufferSource()
      this.currentSource.buffer = audioBuffer
      this.currentSource.connect(this.audioContext.destination)

      // 设置播放结束事件
      this.currentSource.onended = () => {
        this.isPlaying = false
        console.log('音频播放完成')
      }

      // 开始播放
      this.currentSource.start()
      this.isPlaying = true
      console.log('开始播放音频')

      return true
    } catch (error) {
      console.error('播放音频失败:', error)
      this.isPlaying = false
      return false
    }
  }

  /**
   * 停止播放
   */
  stop() {
    if (this.currentSource && this.isPlaying) {
      try {
        this.currentSource.stop()
      } catch (error) {
        // 忽略已经停止的错误
      }
      this.currentSource = null
      this.isPlaying = false
    }
  }

  /**
   * 暂停播放
   */
  pause() {
    if (this.audioContext && this.audioContext.state === 'running') {
      this.audioContext.suspend()
    }
  }

  /**
   * 恢复播放
   */
  resume() {
    if (this.audioContext && this.audioContext.state === 'suspended') {
      this.audioContext.resume()
    }
  }

  /**
   * 设置音量
   */
  setVolume(volume) {
    if (this.currentSource) {
      const gainNode = this.audioContext.createGain()
      gainNode.gain.value = Math.max(0, Math.min(1, volume))
      this.currentSource.disconnect()
      this.currentSource.connect(gainNode)
      gainNode.connect(this.audioContext.destination)
    }
  }

  /**
   * 获取播放状态
   */
  getPlayingState() {
    return this.isPlaying
  }

  /**
   * 释放资源
   */
  dispose() {
    this.stop()

    if (this.audioContext) {
      this.audioContext.close()
      this.audioContext = null
    }
  }
}
